from flask import request, Blueprint
from flask_restful import Api, Resource
from models.init_sqlalchemy import db
from models.models import Comments, User, Posts
import uuid
from flask_jwt_extended import jwt_required, get_jwt_identity
from utils.h_result import HResult
from datetime import datetime
from utils.utils import to_beijing_time

bp = Blueprint('comments', __name__, url_prefix='/comments/')

class AddComment(Resource):
    method_decorators = [jwt_required()]
    
    def post(self):
        data = request.get_json()
        post_id = data.get('post_id')
        content = data.get('content')
        request_comment_id = data.get('request_comment_id')
        current_user = get_jwt_identity()
        
        if not post_id or not content:
            return HResult().get_result('error', '参数错误!')
            
        user = User.query.filter_by(name=current_user).first()
        
        comment = Comments(
            id=str(uuid.uuid4()),
            user_id=user.id,
            post_id=post_id,
            content=content,
            request_comment_id=request_comment_id if request_comment_id else None,
            create_time=to_beijing_time(datetime.utcnow())
        )
            
        db.session.add(comment)
        db.session.commit()
        return HResult().get_result('success', '评论成功!', comment.to_dict())

class DeleteComment(Resource):
    method_decorators = [jwt_required()]
    
    def post(self):
        data = request.get_json()
        comment_ids = data['ids']
        current_user = get_jwt_identity()
        user = User.query.filter_by(name=current_user).first()
        
        for comment_id in comment_ids:
            comment = Comments.query.filter_by(id=comment_id).first()
            if comment and comment.user_id == user.id:
                db.session.delete(comment)
                
        db.session.commit()
        return HResult().get_result('success', '删除成功!')

class CommentInfo(Resource):
    method_decorators = [jwt_required()]
    
    def get(self):
        comment_id = request.args.get('id')
        comment = Comments.query.filter_by(id=comment_id).first()
        
        if not comment:
            return HResult().get_result('error', '评论不存在!')
            
        data = comment.to_dict()
        # 添加关联数据
        data['user'] = comment.user.to_dict()
        if comment.request_comment:
            data['request_comment'] = comment.request_comment.to_dict()
            
        return HResult().get_result('success', data=data)

class QueryPostComments(Resource):
    method_decorators = [jwt_required()]
    
    def get(self):
        post_id = request.args.get('post_id')
        if not post_id:
            return HResult().get_result('error', '参数错误!')
            
        # 检查帖子是否存在且未删除
        post = Posts.query.filter_by(id=post_id, del_flag='1').first()
        if not post:
            return HResult().get_result('error', '帖子不存在!')

        # 首先获取帖子的一级评论
        comments = (Comments.query
                    .filter_by(post_id=post_id)
                    .filter(Comments.request_comment_id == None).all())

        for comment in comments:
            # 获取一级评论下的所有评论, 按照时间排序
            comment.requests = Comments.query.filter_by(origin_comment_id=comment.id).all()
            comment.requests.sort(key=lambda x: x.create_time)  # 使用 lambda 函数按 create_time 排序

        return HResult().get_result('success', data=[{
            'id': comment.id,
            'content': comment.content,
            'user': comment.user.to_dict(),
            'request_comment': comment.request_comment.to_dict() if comment.request_comment else None,
            'requests': [{
                'id': request_comment.id,
                'content': request_comment.content,
                'user': request_comment.user.to_dict(),
                'request_comment': request_comment.request_comment.to_dict() if request_comment.request_comment else None,
                'create_time': request_comment.create_time.strftime('%Y-%m-%d %H:%M:%S')
            } for request_comment in comment.requests] if comment.requests else [],
            'create_time': comment.create_time.strftime('%Y-%m-%d %H:%M:%S')
        } for comment in comments])

api = Api(bp)
api.add_resource(AddComment, '/add/', endpoint='add')
api.add_resource(DeleteComment, '/delete/', endpoint='delete')
api.add_resource(CommentInfo, '/info/', endpoint='info')
api.add_resource(QueryPostComments, '/list/', endpoint='list') 